package com.jixi.common.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jixi.common.exception.HttpRequestException;
import okhttp3.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class CozeChatUtil {
	
	/**
	 * 为了避免用户的输入中包含一些转义字符或双引号而导致JSON无效，需要提前处理。
	 * 别问我怎么发现的，说多了都是泪。
	 */
	private static String escapeJson(String input) {
		return input.replace("\\", "\\\\")
				.replace("\"", "\\\"")
				.replace("\b", "\\b")
				.replace("\f", "\\f")
				.replace("\n", "\\n")
				.replace("\r", "\\r")
				.replace("\t", "\\t");
	}
	
	/**
	 * 发起对话
	 *
	 * @param accessToken access_token
	 * @param username    用户标识（教育局账号用户名）
	 * @param question    用户输入
	 * @return 请求返回参数
	 */
	public static Map<String, Object> startChat(String accessToken, String username, String question) {
		
		final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
		final ObjectMapper objectMapper = new ObjectMapper();
		
		MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
		// 构建请求体
		String requestBody = String.format(
				"{" +
						"\"bot_id\":\"7480825539104833563\"," +
						"\"user_id\":\"%s\"," +
						"\"stream\":false," +
						"\"auto_save_history\":true," +
						"\"additional_messages\":[{" +
							"\"role\":\"user\"," +
							"\"content\":\"%s\"," +
							"\"content_type\":\"text\"" +
						"}]" +
				"}"
		, escapeJson(username), escapeJson(question));
		
		RequestBody body = RequestBody.Companion.create(requestBody, mediaType);
		// 构建请求
		Request request = new Request.Builder()
				.url("https://api.coze.cn/v3/chat")
				.post(body)
				.addHeader("Content-Type", "application/json")
				.addHeader("Authorization", "Bearer " + accessToken)
				.build();
		
		// 发起请求
		try (Response response = HTTP_CLIENT.newCall(request).execute()) {
			if (response.isSuccessful()) {
				if (response.body() != null) {
					String str = response.body().string();
					//System.out.println(str);
					
					// 将整个JSON字符串转换为Map
					Map<String, Object> fullMap = objectMapper.readValue(str, Map.class);
					
					// 提取"data"下的内容
					Map<String, Object> dataMap = (Map<String, Object>) fullMap.get("data");
					
					// 创建一个新的Map来存储需要的字段
					Map<String, Object> resultMap = Map.of(
							"chat_id", dataMap.get("id"),
							"conversation_id", dataMap.get("conversation_id"),
							"status", dataMap.get("status")
					);
					
					return resultMap;
				} else {
					throw new HttpRequestException("响应体为空");
				}
			} else {
				// 输出错误信息
				String errorMessage = "请求失败: " + response.code() + " " + response.message();
				if (response.body() != null) {
					errorMessage += "\n" + response.body().string();
				}
				throw new HttpRequestException(errorMessage);
			}
		} catch (IOException e) {
			throw new HttpRequestException("请求过程中发生IO异常", e);
		}
	}
	
	/**
	 * 查看对话详情
	 *
	 * @param accessToken    access_token
	 * @param conversationId 会话ID
	 * @param chatId         对话ID
	 * @return 请求返回参数
	 */
	public static Map<String, Object> getChatStatus(String accessToken, String conversationId, String chatId) {
		
		final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
		final ObjectMapper objectMapper = new ObjectMapper();
		
		// 对查询参数进行URL编码
		try {
			conversationId = URLEncoder.encode(conversationId, StandardCharsets.UTF_8);
			chatId = URLEncoder.encode(chatId, StandardCharsets.UTF_8);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		// 构建带有查询参数的URL
		String url = String.format("https://api.coze.cn/v3/chat/retrieve?conversation_id=%s&chat_id=%s", conversationId, chatId);
		
		// 构建请求
		Request request = new Request.Builder()
				.url(url)
				.get()
				.addHeader("Content-Type", "application/json")
				.addHeader("Authorization", "Bearer " + accessToken)
				.build();
		
		// 发起请求
		try (Response response = HTTP_CLIENT.newCall(request).execute()) {
			if (response.isSuccessful()) {
				if (response.body() != null) {
					String str = response.body().string();
					//System.out.println(str);
					
					// 将整个JSON字符串转换为Map
					Map<String, Object> fullMap = objectMapper.readValue(str, Map.class);
					
					// 提取"data"下的内容
					Map<String, Object> dataMap = (Map<String, Object>) fullMap.get("data");
					
					// 创建一个新的Map来存储需要的字段
					Map<String, Object> resultMap = Map.of(
							"chat_id", dataMap.get("id"),
							"conversation_id", dataMap.get("conversation_id"),
							"status", dataMap.get("status")
					);
					
					return resultMap;
				} else {
					throw new HttpRequestException("响应体为空");
				}
			} else {
				// 输出错误信息
				String errorMessage = "请求失败: " + response.code() + " " + response.message();
				if (response.body() != null) {
					errorMessage += "\n" + response.body().string();
				}
				throw new HttpRequestException(errorMessage);
			}
		} catch (IOException e) {
			throw new HttpRequestException("请求过程中发生IO异常", e);
		}
	}
	
	/**
	 * 查看对话消息详情
	 *
	 * @param accessToken    access_token
	 * @param conversationId 会话ID
	 * @param chatId         对话ID
	 * @return 请求返回参数
	 */
	public static Map<String, Object> getChatMessage(String accessToken, String conversationId, String chatId) {
		
		final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
		final ObjectMapper objectMapper = new ObjectMapper();
		
		// 对查询参数进行URL编码
		try {
			conversationId = URLEncoder.encode(conversationId, StandardCharsets.UTF_8);
			chatId = URLEncoder.encode(chatId, StandardCharsets.UTF_8);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		// 构建带有查询参数的URL
		String url = String.format("https://api.coze.cn/v3/chat/message/list?conversation_id=%s&chat_id=%s", conversationId, chatId);
		
		// 构建请求
		Request request = new Request.Builder()
				.url(url)
				.get()
				.addHeader("Content-Type", "application/json")
				.addHeader("Authorization", "Bearer " + accessToken)
				.build();
		
		// 发起请求
		try (Response response = HTTP_CLIENT.newCall(request).execute()) {
			if (response.isSuccessful()) {
				if (response.body() != null) {
					String str = response.body().string();
					//System.out.println(str);
					
					// 将JSON字符串解析为JsonNode对象
					JsonNode rootNode = objectMapper.readTree(str);
					
					// 获取"data"数组
					JsonNode dataArray = rootNode.path("data");
					
					Map<String, Object> resultMap = new HashMap<>();
					// 遍历"data"数组中的每个元素
					for (JsonNode element : dataArray) {
						String type = element.path("type").asText();
						String contentType = element.path("content_type").asText();
						
						// 检查"type"和"content_type"
						if ("answer".equals(type) && "text".equals(contentType)) {
							// 提取"content"
							resultMap.put("content", element.path("content").asText());
						}
					}
					
					return resultMap;
				} else {
					throw new HttpRequestException("响应体为空");
				}
			} else {
				// 输出错误信息
				String errorMessage = "请求失败: " + response.code() + " " + response.message();
				if (response.body() != null) {
					errorMessage += "\n" + response.body().string();
				}
				throw new HttpRequestException(errorMessage);
			}
		} catch (IOException e) {
			throw new HttpRequestException("请求过程中发生IO异常", e);
		}
	}
	
}
